#include "xq_player.h"
#include <media/AudioTrack.h>
const float kMaxRequiredSpeed = 1.0f; // for PCM tracks allow up to 8x speedup.
using namespace android;
using android::content::AttributionSourceState;

sp<AudioTrack> t;

void * xq_player_create(int type,int sampleRate,int channels,int bits)
{
	audio_format_t format = ((bits == 16)?AUDIO_FORMAT_PCM_16_BIT:AUDIO_FORMAT_PCM_8_BIT);
	audio_channel_mask_t channelMask = ((channels == 1)?AUDIO_CHANNEL_OUT_MONO:AUDIO_CHANNEL_OUT_STEREO);


	audio_session_t session ;
	AttributionSourceState attributionSource;
	audio_port_handle_t deivceId = AUDIO_PORT_HANDLE_NONE;
    t = new AudioTrack(
    		AUDIO_STREAM_DEFAULT,
			sampleRate,
            format,
            channelMask,
            0,
			AUDIO_OUTPUT_FLAG_NONE,
            nullptr, // callback
            0, // notification frames
			session,/**mSessionId**/
            AudioTrack::TRANSFER_SYNC,
			nullptr, // offload info
			attributionSource,/**mAttributionSource**/
			nullptr,/**mAttributes**/
            false,/**doNotReconnect**/
			kMaxRequiredSpeed,/**targetSpeed**/
			deivceId/**mSelectedDeviceId**/);

    if( t != nullptr)
    {
    	status_t status = t->initCheck();
    	if(status != NO_ERROR){
    		printf("xq_player init error:%d\n",status);
    		t = nullptr;
    		return nullptr;
    	}
    	t->start();
    	printf("xq_player init success:%d\n",status);
    }

	return nullptr;
}

int xq_player_write(void *handle, void* data,int len)
{
	if(t != nullptr){
		//write(const void* buffer, size_t userSize, bool blocking)
		ssize_t ret = t->write(data,len,true);
		printf("xq_player_write success ret = %d \n",ret);
	}else{
		printf("xq_player_write fail \n");
	}

	return 0;
}


int xq_player_destroy(void *handle)
{
	if(t != nullptr){
		t->stop();
		t->flush();
		t = nullptr;
	}

	return 0;
}



